package sinaLogin.com.com.sinaweibo;

import java.io.InputStream;
import java.net.CookieManager;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;

import sinaLogin.com.com.base.texthelper.StreamFormator;
import com.sinaweibo.SinaSSOEncoder;

public class SinaLogin {
    private String account;
    private String pwd;
    private DefaultHttpClient dhc;
    private String nonce;
    private String su;
    private String servertime;
    private String sp;
    private String cookiestr;//httpclient�����Ǳ����ύ�Ĳ����ʾ�Ѿ���¼��
    
    public SinaLogin(DefaultHttpClient dhc,String account,String pwd){
        this.dhc = dhc;
        this.account = account;
        this.pwd = pwd;
        this.su = this.encodeAccount(this.account);
        this.nonce = this.makeNonce(6);
        this.servertime = this.getServerTime();
        this.sp = new SinaSSOEncoder().encode(this.pwd, this.servertime, this.nonce);
        this.cookiestr = this.initCookieString();
    }
    
    public boolean connect(){
        if(this.dhc == null){
            return false;
        }
        boolean result = true;
        String cmturl = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.16)";
        try{
            System.out.println("start connect...");
            HttpPost post = new HttpPost(cmturl);
            ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair("entry", "weibo"));
            params.add(new BasicNameValuePair("gateway", "1"));
            params.add(new BasicNameValuePair("from", ""));
            params.add(new BasicNameValuePair("savestate", "7"));
            params.add(new BasicNameValuePair("useticket", "1"));
            params.add(new BasicNameValuePair("ssosimplelogin", "1"));
            params.add(new BasicNameValuePair("vsnf", "1"));
            params.add(new BasicNameValuePair("vsnval", ""));
            params.add(new BasicNameValuePair("su", this.su));
            params.add(new BasicNameValuePair("service", "miniblog"));
            params.add(new BasicNameValuePair("servertime",this.servertime));
            params.add(new BasicNameValuePair("nonce", this.nonce));
            params.add(new BasicNameValuePair("pwencode", "wsse"));
            params.add(new BasicNameValuePair("sp",this.sp));
            params.add(new BasicNameValuePair("encoding", "UTF-8"));
            params.add(new BasicNameValuePair("url", "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"));
            params.add(new BasicNameValuePair("returntype", "META"));
            UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(params);
            post.setEntity(formEntiry);
            HttpResponse hr = this.dhc.execute(post);
            //���cookie����
            String cookiestr;
            for(int i=0;i<hr.getHeaders("Set-Cookie").length;i++){
                //System.out.println(hr.getHeaders("Set-Cookie")[i].toString());
                cookiestr = hr.getHeaders("Set-Cookie")[i].toString().replace("Set-Cookie:", "").trim();
                this.cookiestr += cookiestr.substring(0,cookiestr.indexOf(";")) + ";";
            }
            this.cookiestr += "un="+ this.account;
            
            HttpEntity hentity = hr.getEntity();
            InputStream inputstream = hentity.getContent();
            String tmp = StreamFormator.getString(inputstream, "GBK");
            if(tmp.indexOf("正在登录")>0){
                result = true;
            }else{
                result =false;
            }
            inputstream.close();
            System.out.println("end connect...");
            //return this.commenttext;
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
    
    private String initCookieString(){
        StringBuilder  sb = new StringBuilder();
//        sb.append("SSCSum=4;");
//        sb.append("UOR=,weibo.com,;");
//        sb.append("USRHAJAWB=usrmdins13148;");
//        sb.append("_s_tentry=-;");
//        sb.append("Apache=1398910433053.9702.1321158799648;");
//        sb.append("ULV=1321158799660:4:4:3:1398910433053.9702.1321158799648:1321156589166;");
//        sb.append("SinaRot//=39;");
//        sb.append("_s_acc=2599263,;");
        //sb.append("SUE=es%3De8bcdd332b7a40bb92c13e04df44282e%26ev%3Dv1%26es2%3D0c20322bcbab1cf60e280e8f8d499850%26rs0%3DAJsxWX%252BHkF4qeiFpnNawE6LnwTe1YKFFOIiLHIOHVbzgypyaFvK2eGMPv8aO9AgJ0IVHRVKp6t4ETQDAifYcZq8q0MySW248THLxBY%252FPHVgnLoTf4X71mkFJoajAbTSpUEfoDJ7Y5prlLQxjfhqZVgxVJKrAblYzz8fGOUAyd3A%253D%26rv%3D0;");
        //sb.append("SUP=cv%3D1%26bt%3D1321161096%26et%3D1321247496%26lt%3D1%26uid%3D1985472791%26user%3D464289588%2540qq.com%26ag%3D4%26name%3D464289588%2540qq.com%26nick%3D464289588%26sex%3D%26ps%3D0%26email%3D%26dob%3D%26ln%3D1985472791%26os%3D%26fmp%3D%26lcp%3D%26us%3D0%26vf%3D0;");
//        sb.append("ALF=1321765893;");
//        sb.append("SSOLoginState=1321161097;");
        sb.append("wvr=4;");
//        sb.append("un=464289588@qq.com;");
//        sb.append("ads_ck=1;");
//        sb.append("USRHAWB=usrmdins212_170;");
//        sb.append("__utma=182865017.1793921192.1321161631.1321161631.1321161631.1;");
//        sb.append("__utmc=182865017;");
//        sb.append(" __utmz=182865017.1321161631.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);");
//        sb.append(" SINAGLOBAL=1398910433053.9702.1321158799648");
        return sb.toString();
    }
    
    public String getCookieString(){
        return this.cookiestr;
    }
    
    private String encodeAccount(String account){
        return Base64.encodeBase64String(URLEncoder.encode(account).getBytes());
    }
    
    private String makeNonce(int len){
        //var makeNonce=function(len)
        //{var x="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        //var str="";for(var i=0;i<len;i++)
        //{str+=x.charAt(Math.ceil(Math.random()*1000000)%x.length)}return str};
        String x="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String str = "";
        for(int i=0;i<len;i++){
            str+=x.charAt((int) (Math.ceil(Math.random()*1000000)%x.length()));
        }
        return str;
    }
    
    private String getServerTime(){
        long servertime = new Date().getTime()/1000;
        System.out.println("servertime:" + servertime);
        return String.valueOf( servertime);
    }

    private BasicClientCookie getCookieFormString(String str){
        str = str.replace("Set-Cookie: ", "");
        String name = str.substring(0,str.indexOf("="));
        System.out.println(name);
        String value = str.substring(str.indexOf("=")+1,str.indexOf(";"));
        System.out.println(value);
        BasicClientCookie bcc = new BasicClientCookie(name,value);
        int start,end;
        if(str.indexOf("domain=")>0){
            start = str.indexOf("domain=");
            end = str.indexOf(";", start);
            if(end>0){
                bcc.setDomain(str.substring(start+7, str.indexOf(";", start)));
            }else{
                bcc.setDomain(str.substring(start+7, str.length()-1));
            }
        }
        if(str.indexOf("path=")>0){
            start = str.indexOf("path=");
            end = str.indexOf(";", start);
            if(end>0){
                bcc.setPath(str.substring(start+5, end));
            }else{
                bcc.setPath(str.substring(start+5,str.length()-1));
            }
        }
        return bcc;
    }
}
